<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends MY_Controller
{
	function __construct()
	{
		parent::__construct();
		$this->load->library(array("form_validation", "session"));
	}
	
	function index()
	{
		$this->session->keep_flashdata("return_url");
		$this->session->set_flashdata("error", "Username or password are wrong");
		//$this->template->load("layout", "home_view");
//		$this->load->view("login_view");
	}

	function try_login()
	{
		$this->session->keep_flashdata("return_url");
		if($this->session->userdata("logged") != 1){
			
			$this->form_validation->set_rules('loginName', 'Login', 'trim|required');
			$this->form_validation->set_rules('loginPassword', 'Password', 'trim|required');
	
			
			if ($this->form_validation->run() == FALSE){
				$data["error"] = validation_errors();
				echo json_encode($data);
			}
			else{
				switch ($this->input->post("accountType")){
					case "ewallet":{
						$this->load->model("ewallet_model", "model", TRUE);
						break;
					}
					case "ip": {
						$this->load->model("payments_model", "model", TRUE);
						break;
					}
				}
				if($this->input->post("accountType")){
					$d['USER_ID'] = $this->input->post("loginName");
					$d['USER_PASSWD'] = sha1($this->input->post("loginPassword"));
	
					$user = $this->model->user_login($d);
					if($user){
						$usr['type'] = $this->input->post("accountType");
						unset($user['USER_PASSWD']);
	//					unset($user['ID']);
						unset($user['MM_NAME']);
						$this->load->database('default', TRUE, TRUE);
						$this->session->set_userdata($usr);
						$this->session->set_userdata($user);
						$this->set_logged(1);
//						if($this->session->flashdata("return_url")){
//							$data['redirect'] = site_url("user/" . $this->session->flashdata("return_url"));
//						}
//						else{
						$data['redirect'] = site_url("user/account");
//						}
					}
					else {
						$data["error"] = "Username or password are wrong";
						$data["islogin"] = true;
					}
					echo json_encode($data);
					
				}
			}
		}
		else{
			if($this->session->flashdata("return_url")){
				$data['redirect'] = site_url("user/" . $this->session->flashdata("return_url"));
			}
			else{
				$data['redirect'] = site_url("home");
			}
			echo json_encode($data);
		}
		
	}
}